<?php
/**
 * Created by PhpStorm.
 * User: 雨寒
 * Date: 2018/8/17
 * Time: 下午2:01
 */

namespace app\common\model;

use Phinx\Config;
use think\Cache;
use think\Db;
use think\exception\DbException;
use app\admin\model\Wallet;
use app\common\model\Settings;
//token加密密钥
define("H_TOKEN_SECRET", "h_link.com");

class User extends Common
{

    /**
     * 判断用户是否存在
     *
     * @param string $account 待查询用户的ID或手机号
     * @return array|null 若用户存在则返回用户数组，否则返回null
     */
    static public function exists($account)
    {
        $user = Db::name("user")
            ->where("id|mobile", "=", $account)
            ->find();

        return $user;
    }

    /**
     * 注册用户
     *
     * @param string $real_name 真实姓名
     * @param string $mobile 手机号
     * @param string $password 密码
     * @param $confirmpassword
     * @param int $parent_mobile
     * @param $duties_id
     * @param $industry_id
     * @param $server
     * @param $abstract
     * @return mixed
     * @throws DeveloperException
     * @throws ServerException
     * @throws UserException
     */
    static public function register($real_name,$mobile,$password,$confirmpassword,$parent_mobile=0,$duties_id,$industry_id,$server,$abstract,$bussiness_id)
    {
        //检测用户是否已存在
        if (self::exists($mobile))
        {
            throw new UserException("手机号" . $mobile . "已被注册使用！");
        }
        if($password!=$confirmpassword)
        {
            throw new UserException("两次密码不一样！");
        }

//        if($second_password!=$second_confirmpassword)
//        {
//            throw new UserException("两次输入二级密码不一样！");
//        }
        if(!empty($parent_mobile))
        {
            $parent=self::exists($parent_mobile);
            if(empty($parent))
            {
                throw new DeveloperException("没有此推荐人！");
            }
            $rate=Settings::getSystem();
            Wallet::addDelCoin($parent_mobile,$rate['invite_reward'],1,'下级注册赠送H币');
            $parent_id=$parent['id'];
        }else{
            $parent_id=0;
        }

        //用户信息
        $user = array(
            'mobile' => $mobile,
            'parent_id' => $parent_id,
            'real_name' => $real_name,
            'duties_id' => $duties_id,
            'industry_id' => $industry_id,
            'server' => $server,
            'abstract' => $abstract,
            'bussiness_id' => $bussiness_id,
            'password' => md5($password),
//            'second_password' => base64_encode(base64_encode($second_password)),
            'create_time' => now_datetime(),
            'update_time' => now_datetime()
        );

        //创建用户
        $result = Db::name("user")->insertGetId($user);

        if (empty($result))
        {
            throw new ServerException("创建新用户失败！" . __FILE__ . __LINE__);
        }
        //返回用户uid
        return $result;
    }
    

    /**
     * 登录用户
     *
     * @param $mobile
     * @param $password
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws UserException
     */
    static public function login($mobile, $password,$captcha)
    {
        if(empty($password)&&empty($captcha))
        {
            throw new UserException("请填写密码或者验证码！");
        }
        //查找用户
        $user = self::exists($mobile);

        //判断用户存在性
        if (!$user)
        {
            throw new UserException("用户【" . $mobile . "】不存在！");
        }

        /*密码登录*/
       if(!empty($password))
       {
           //判断密码是否正确
           if (md5($password) != $user["password"])
           {
               throw new UserException("登录密码错误！");
           }
       }

        if(!empty($captcha))
        {
            //判断验证码是否正确
            SMS::verifyCaptcha($mobile, $captcha);

        }

        //判断是否被拉黑
        if ($user["in_blacklist"])
        {
            throw new UserException("您的账号已被拉黑，请及时联系管理员处理！");
        }

        //token
        $token = self::getAccessToken($user);
        /*添加登录时间,登录次数*/
        $last_time=date("Y-m-d",$user['last_login_time']);
        $now_time=date("Y-m-d");
        $arr['last_login_time']=time();
        if($now_time>$last_time)
        {
            $arr['login_days']=$user['login_days']+1;
        }
        Db::name('user')
            ->where('id',$user['id'])
            ->update($arr);

        //返回token
        return array(
            "token" => $token,
            "bussiness_id" => $user["bussiness_id"],
            "uid" => $user["id"],
        );
    }

    /**
     * 忘记密码重新设置密码
     * @param String $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $confirmpassword 确认密码密码
     * @throws UserException
     */

    static public function forgetPassword($mobile,$newpassword,$confirmpassword)
    {
        //判断用户是否存在
        $user = User::exists($mobile);

        //判断确认密码是否相同
        if ($newpassword != $confirmpassword)
        {
            throw new UserException("请重新填写确认密码!");
        }


        //判断用户存在性
        if (!$user)
        {
            throw new UserException("用户【" . $mobile . "】不存在！");
        }

        //修改密码
        $result = Db::name("user")
            ->where("id", "=", $user["id"])
            ->setField("password", md5($newpassword));

    }

    /**
     * 删除会员
     *
     * @param string $userId 待删除的会员ID
     * @param bool $isTotal 如果为true，则彻底删除数据；否则，添加删除字段
     */
    static public function remove($userId, $isTotal = false)
    {
        //修改关系链
        {
            //上级ID
            $parentId = Db::name("user")
                ->where("id", $userId)
                ->where("is_valid", 1)
                ->value("parent_id");

            //将所有下级拉取到上级
            Db::name("user")
                ->where("parent_id", $userId)
                ->where("is_valid", 1)
                ->setField("parent_id", $parentId);
        }

        //删除会员
        if ($isTotal)
        {
            Db::name("user")
                ->where("id", $userId)
                ->delete();
        }
        else
        {
            Db::name("user")
                ->where("id", $userId)
                ->setField("is_valid", 0);
        }
    }

    /**
     * 修改密码
     *
     * @param string $user 用户
     * @param string $oldpassword 旧密码
     * @param string $newpassword 新密码
     * @param string $confirmpassword 确认密码
     * @throws UserException
     */
    static public function changePassword($user, $oldpassword,$newpassword,$confirmpassword)
    {

        //判断旧密码对不对
        if (md5($oldpassword) != $user["password"])
        {
            throw new UserException("旧密码错误！");
        }

        //新密码与确认密码是否一致
        if ($confirmpassword != $newpassword)
        {
            throw new UserException("新密码与确认密码不一致！");
        }

        //新密码是否未改变
        if ($oldpassword == $newpassword)
        {
            throw new UserException("新密码不能与旧密码相同！");
        }

        //修改密码
        $result = Db::name("user")
            ->where("id", "=", $user["id"])
            ->setField("password", md5($newpassword));
    }

    /**
     * 根据token获取用户信息
     *
     * @param $token
     * @return array|null
     * @throws TokenException
     * @throws UserException
     */
    static public function userFromToken($token)
    {
        //判断token是否为空
        if (empty($token))
        {
            throw new TokenException("token字段为空！");
        }

        //加密密钥
        $secret = md5(H_TOKEN_SECRET);

        //解析token
        $tempString = aes_decrypt($secret, $token);

        //用户信息
        $userInfo = json_decode($tempString, true);

        //判断用户信息是否为空
        if (empty($userInfo) ||
            !array_key_exists("uid", $userInfo) ||
            !array_key_exists("password", $userInfo))
        {
            throw new TokenException("token验证失败！");
        }

        //token名称
        $tokenName = "access_token-" . $userInfo["uid"];

        //判断token是否存在
        if (!Cache::has($tokenName))
        {
            throw new TokenException("尚未登录，请进行登录操作！");
        }

//        //判断是否为异地登录
//        if (Cache::get($tokenName) != $token)
//        {
//            throw new TokenException("您的账号已在异地登录，若非本人操作，请及时修改密码！");
//        }
//
//        //判断登录是否已过期
//        if ($userInfo["due_time"] < time())
//        {
//            throw new TokenException("登录已过期，请重新登录！");
//        }

        //判断用户是否存在
        $user = self::exists($userInfo["uid"]);

        //判断用户是否存在
        if (empty($user))
        {
            throw new TokenException("用户不存在，请重新登录！");
        }

        //判断密码是否已修改
        if ($user["password"] != $userInfo["password"])
        {
            throw new TokenException("登录密码已修改，请重新登录！");
        }

        //判断是否被拉黑
        if ($user["in_blacklist"])
        {
            throw new UserException("您的账号已被拉黑，请及时联系管理员处理！");
        }

        //判断是否有头像
//        if (empty($user["avatar"]) || !check_url($user["avatar"]))
//        {
//            $user["avatar"] = get_whole_image("/static/images/default_icon.png");
//        }

        return $user;
    }

    /**
     * 修改用户头像
     *
     * @param array $user 用户
     * @param string $avatar 待修改的头像
     * @throws DeveloperException
     * @throws UserException
     */
    static public function modifyAvatar($user, $avatar)
    {
        //检测头像是否可用
//        if (!check_web_image($avatar))
//        {
//            throw new DeveloperException("非法头像地址！");
//        }

        //更新用户头像
        Db::name("user")
            ->where("id", $user["id"])
            ->setField("avatar", $avatar);
    }

    /**
     * 修改用户昵称
     *
     * @param array $user 用户
     * @param $type 修改类型（1：姓名，2：邮箱，3：简介,4:服务项目）
     * @param $content
     * @throws UserException
     * @internal param string $nickname 昵称
     */
    static public function setUpdate($user,$type,$content)
    {

        if(empty(trim($content))){
            throw new UserException("修改内容不能为空！");
        }

        if($type==1)
        {
            //更新用户昵称
            Db::name("user")
                ->where("id", $user["id"])
                ->setField("real_name", $content);
        }elseif($type==2)
        {
            //更新用户邮箱
            Db::name("user")
                ->where("id", $user["id"])
                ->setField("email", $content);
        }elseif($type==3)
        {
            //更新用户简介
            Db::name("user")
                ->where("id", $user["id"])
                ->setField("abstract", $content);
        }elseif($type==4)
        {
            //更新用户服务项目
            Db::name("user")
                ->where("id", $user["id"])
                ->setField("server", $content);
        }else{
            return;
        }

    }

    /**
     * 更换手机号
     *
     * @param array $user 用户
     * @param string $mobile 手机号
     * @throws UserException
     */
    static public function modifyMobile($user, $mobile)
    {
        //判断手机是否被使用
        if (self::exists($mobile))
        {
            throw new UserException("手机号【" . $mobile . "】已被注册使用！");
        }

        //更换手机号
        Db::name("user")
            ->where("id", $user["id"])
            ->setField("mobile", $mobile);
    }

    /**
     * 意见反馈
     *
     * @param array $user 用户
     * @param string $content 反馈内容
     * @throws DeveloperException
     */
    static public function memberSuggest($user, $content)
    {
        $data = array(
            "uid" => $user["id"],
            "suggestion" => $content,
            "create_time" => now_datetime()
        );

        $res=Db::name("suggestion")->insert($data);
        if(!$res)
        {
            throw new DeveloperException('操作失败！');
        }
    }

    /**
     * 获取登录用户的token
     *
     * @param $user
     * @return string
     */
    static private function getAccessToken($user)
    {
        //加密密钥
        $secret = md5(H_TOKEN_SECRET);

        //临时字符串
        $tempString = json_encode(array(
            "uid" => $user["id"],
            "password" => $user["password"],
            "due_time" => time() + 1 * 24 * 60 * 60,
            "random" => rand(100000, 999999),
        ));

        $token = aes_encrypt($secret, $tempString);

        //存储token
        Cache::set("access_token-" . $user["id"], $token);

        //返回token
        return $token;
    }

    /**
     * 会员详情
     *
     * @param string $account 待查询用户的ID
     * @return array|null 若用户存在则返回用户数组，否则返回null
     */
    static public function memberInfo($account)
    {
        $user=self::exists($account);

        /*商会名称加到会员信息*/
        if($user['bussiness_id']>0)
        {
            $bussiness=Db::name('bussiness')
                ->where('id',$user['bussiness_id'])
                ->value('title');
            $user['bussiness_title']=$bussiness;
        }

        /*处理会员的荣誉*/
        if(!empty($user['honor']))
        {
            $honor=explode('*',$user['honor']);
            $user['honor']=$honor;
        }else{
            $user['honor']=array();
        }
        /*部门信息加到会员信息*/
        if($user['department_id']>0)
        {
            $department=Db::name('department')
                ->where('id',$user['department_id'])
                ->value('title');
            $user['department_title']=$department;
        }

        //*职务信息加到会员信息*/
        if($user['duties_id']>0)
        {
            $duties=Db::name('duties')
                ->where('id',$user['duties_id'])
                ->value('title');
            $user['duties_title']=$duties;
        }

        /*三个参数*/
        $connection_num=Db::name('user_follow')
            ->where('tag','like','%'.$user['id'].'%')
            ->count();
        $all_num=Db::name('user')
            ->where('in_blacklist',0)
            ->count();
        if(empty($all_num))
        {
            $connection_rate=0;
        }else{
            $connection_rate=ceil($connection_num/$all_num*100);
        }


        $now_time=strtotime(date("Y-m-d"));
        $start_time=strtotime(date("Y-m-d",$user['create_time']));
        $all_days=($now_time-$start_time)/86400;
        if(empty($all_days))
        {
            $active_rate=100;
        }else{
            $active_rate=ceil($user['login_days']/$all_days*100);
        }

        $comment=Db::name('order_comment')
            ->where('receive_uid',$user['id'])
            ->field('star')
            ->select();
        if(empty($comment))
        {
            $credit_rate=100;
        }else{
            $credit_sum=0;
            foreach ($comment as $item)
            {
                $credit_sum+=$item['star'];
            }
            $credit_rate=ceil($credit_sum/count($comment)/5*100);
        }

        /*六角形*/
        $data_arr=json_encode(array(
//            array("item"=>"影响力","a"=>10),
            array("item"=>"人脉力","a"=>$connection_rate),
//            array("item"=>"号召力","a"=>30),
//            array("item"=>"领导力","a"=>40),
            array("item"=>"活跃度","a"=>$active_rate),
            array("item"=>"信用度","a"=>$credit_rate),
        ));
        $user['date_arr']=$data_arr;

        return $user;

    }


}